package com.zb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.ZjCodeUserChangeLog;
import com.zb.mapper.ZjCodeUserChangeLogMapper;
import com.zb.result.PageUtil;
import com.zb.service.ZjCodeUserChangeLogService;
import com.zb.vo.CodeUserChangeCountVo;
import com.zb.vo.CodeUserChangeLogListVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 编码用户变更记录表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-09-04
 */
@Service
public class ZjCodeUserChangeLogServiceImpl extends ServiceImpl<ZjCodeUserChangeLogMapper, ZjCodeUserChangeLog> implements ZjCodeUserChangeLogService {
    @Resource
    private ZjCodeUserChangeLogMapper codeUserChangeLogMapper;

    // 获取变更记录列表
    @Override
    public Map<String, Object> getList(Long codeId, PageUtil pageUtil) {
        PageUtil.setPageLimit(pageUtil);
        QueryWrapper<ZjCodeUserChangeLog> wrapper = new QueryWrapper<>();
        wrapper.select("id", "username", "phone", "province", "city", "area", "town", "address", "remark", "gmt_create");
        wrapper.eq("code_id", codeId);
        wrapper.orderByDesc("gmt_create");
        Page<ZjCodeUserChangeLog> page = this.page(new Page<>(pageUtil.getPage(), pageUtil.getLimit()), wrapper);

        // 查询变更次数集合
        List<CodeUserChangeCountVo> logListVos = codeUserChangeLogMapper.getChangeCountByCodeId(codeId);

        List<CodeUserChangeLogListVo> voList = page.getRecords().stream().map(log -> {
            CodeUserChangeLogListVo vo = new CodeUserChangeLogListVo();
            BeanUtils.copyProperties(log, vo);
            vo.setCreateTime(log.getGmtCreate());
            vo.setCreateEmp(log.getCreateEmp());
            vo.setCount(logListVos.stream().filter(co -> Objects.equals(vo.getId(), co.getId())).map(CodeUserChangeCountVo::getCount).findFirst().orElse(0));
            return vo;
        }).toList();
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), voList);
    }
}
